<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>chatgpt</title>
</head>
<script>

async function send(){
  const $input=document.getElementById('textarea');
  const value=$input.value;

  if(!value){
    return;
  }
 // 通过 new EventSource 开启 SSE
 const source = new EventSource('/chatgpt');

 source.addEventListener('open', () => {
   console.log('建立连接');
 });

 source.addEventListener('error', (err) => {
   console.log('连接出错:', err);
   source.close();
 });

 source.addEventListener('message', (event) => {
   // 结束则关闭链接
   if (event.data.trim() === '[DONE]') {
     source.close();
   }
   console.log(event.data)
 });
//const response = await fetch('/chatgpt',{
  //  method:'POST',
    // body: value
//});

//const reader = response.body.getReader();
//console.log("======>",reader)
//while (true) {
 // const { value, done } = await reader.read();
 // if (done) break;
 // var _reader = new FileReader();
 // const decoder = new TextDecoder('utf-8');
 
 // console.log('Received',    decoder.decode(value));
//}

console.log('Response fully received');
}
</script>
<body>
   <textarea id="textarea"></textarea>
   <button  onclick="send()">点击</button>
</body>
</html>